// src/utils/web3Utils.js

import { ethers } from "ethers";
let currentListener = null;
// 连接MetaMask并获取地址
export const connectMetaMask = async () => {
  if (typeof window.ethereum !== "undefined") {
    await window.ethereum.request({ method: "eth_requestAccounts" });
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();
    const address = await signer.getAddress();
    return { provider, signer, address };
  } else {
    throw new Error("请安装MetaMask!");
  }
};

// 请求签名
export const signMessage = async (signer, message) => {
  const signature = await signer.signMessage(message);
  return signature;
};

// 监听转账
export const listenToTokenTransfers = (provider, contractAddress, address) => {
  console.log("监听转账...", provider, contractAddress, address);
  if (!address) {
    throw new Error("address 不能为空");
  }

  // 取消当前的监听器（如果存在）
  if (currentListener) {
    provider.off(currentListener);
  }

  const formattedAddress = "0x000000000000000000000000" + address.slice(2);

  const filter = {
    fromBlock: "latest",
    address: [contractAddress],
    topics: [
      "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
      null,
      formattedAddress,
    ],
  };

  // 设置新的监听器
  currentListener = filter;
  console.log(54);
  provider.on(filter, (log, event) => {
    console.log(328, log, event);
  });
};
// 停止监听
export const stopListening = (provider) => {
  if (currentListener) {
    provider.off(currentListener);
    currentListener = null;
  }
};
